import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HttpService} from "../../providers/HttpService";
import echarts from 'echarts';

/**
 * Generated class for the StockPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-quotation-detail',
  templateUrl: 'quotation-detail.html',
})
export class QuotationDetailPage {

    quotation: any;
    tab_position: number = 0;
    query_list: any[] = [
        {
            title: '分时',
            value: 'Min01'
        },
        {
            title: '1小时',
            value: 'Min60'
        },
        {
            title: '日线',
            value: 'Day'
        },
        {
            title: '周线',
            value: 'Week'
        },
        {
            title: '月线',
            value: 'Month'
        },
        {
            title: '1分钟',
            value: 'Min01'
        },
        {
            title: '3分钟',
            value: 'Min03'
        },
        {
            title: '5分钟',
            value: 'Min05'
        },
        {
            title: '15分钟',
            value: 'Min15'
        },
        {
            title: '30分钟',
            value: 'Min30'
        },
    ];
    dataList: Array<any> = [];

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private httpService: HttpService) {
        this.quotation = this.navParams.get('data');
    }

    ionViewWillLoad() {
        this.getQuotationData(this.query_list[this.tab_position].value);
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad QuotationDetailPage');
    }

    getMasterIconName(range: string) {
        let value = Number(range);
        if (value > 0) {
            return 'ios-arrow-round-up';
        } else if (value < 0) {
            return 'ios-arrow-round-down';
        } else {
            return 'ios-arrow-round-down';
        }
    }

    getMasterStyle(range: string) {
        let value = Number(range);
        return {
            'normal-master': value == 0,
            'up-master': value > 0,
            'down-master': value < 0
        };
    }

    getSlaveStyle(range: string) {
        let value = Number(range);
        return {
            'normal-slave': value == 0,
            'up-slave': value > 0,
            'down-slave': value < 0
        };
    }

    getTabBtnStyle(index: number) {
        return {
            'tab-btn-select': this.tab_position == index,
            'tab-btn-none': this.tab_position != index
        };
    }

    onTabBtnSelected(index: number, value: string) {
        this.tab_position = index;

        this.getQuotationData(value);
    }

    getQuotationData(type: string) {
        this.httpService.instance()
            .setUrl('/gold/getQuotationData')
            .setQuery({
                type: type,
                code: this.quotation.key
            })
            .getRequest()
            .then(res => {
                if (res.status == 0) {
                    if (res.data.totalCount > 0) {
                        this.dataList = res.data.totalList.reverse();
                        if (this.tab_position > 0) {
                            this.showStockChart();
                        } else {
                            this.showLineChart();
                        }
                    }
                } else {
                    console.log(res.msg);
                }
            });
    }

    showStockChart() {
        function calculateMA(dayCount, data) {
            let result = [];
            for (let i = 0, len = data.length; i < len; i++) {
                if (i < dayCount) {
                    result.push('-');
                    continue;
                }
                let sum = 0;
                for (let j = 0; j < dayCount; j++) {
                    sum += data[i - j][1];
                }
                result.push((sum / dayCount).toFixed(2));
            }
            return result;
        }

        let stockChart = echarts.init(document.getElementById('stock'));
        let colorList = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'];
        let labelFont = 'bold 12px Sans-serif';

        let dateArray = [];
        let dataList = [];
        let volumes = [];

        for (let i = 0; i < this.dataList.length; i++) {
            let priceDate = this.dataList[i];
            dateArray.push(priceDate.date);
            let priceArray = [];
            priceArray.push(Number(priceDate.openPrice));
            priceArray.push(Number(priceDate.closePrice));
            priceArray.push(Number(priceDate.lowPrice));
            priceArray.push(Number(priceDate.highPrice));
            priceArray.push(priceDate.amount);
            dataList.push(priceArray);
            volumes.push(priceDate.amount);
        }

        let dataMA5 = calculateMA(5, dataList);
        let dataMA10 = calculateMA(10, dataList);
        let dataMA20 = calculateMA(20, dataList);

        let stockOption = {
            animation: false,
            color: colorList,
            title: {
                show: false,
                left: 'center',
                text: '移动端 K线图'
            },
            legend: {
                show: true,
                top: 10,
                textStyle: {
                    color: '#ffffff'
                },
                data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
            },
            tooltip: {
                show: false,
                triggerOn: 'none',
                transitionDuration: 0,
                confine: true,
                bordeRadius: 4,
                borderWidth: 1,
                borderColor: '#333',
                backgroundColor: 'rgba(255,255,255,0.9)',
                textStyle: {
                    fontSize: 12,
                    color: '#333'
                },
                position: function (pos, params, el, elRect, size) {
                    let obj = {
                        top: 60
                    };
                    obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
                    return obj;
                }
            },
            axisPointer: {
                link: [{
                    xAxisIndex: [0, 1]
                }]
            },
            dataZoom: [{
                disabled: false,
                type: 'slider',
                xAxisIndex: [0, 1],
                realtime: false,
                start: 90,
                end: 100,
                top: 45,
                height: 20,
                handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '120%'
            }, {
                disabled: false,
                type: 'inside',
                xAxisIndex: [0, 1],
                start: 1,
                end: 100,
                top: 30,
                height: 20
            }],
            xAxis: [{
                type: 'category',
                data: dateArray,
                boundaryGap : false,
                axisLine: { lineStyle: { color: '#777' } },
                axisLabel: {
                    formatter: function (value) {
                        return echarts.format.formatTime('MM-dd', value);
                    }
                },
                min: 'dataMin',
                max: 'dataMax',
                axisPointer: {
                    show: true
                }
            }, {
                type: 'category',
                gridIndex: 1,
                data: dateArray,
                scale: true,
                boundaryGap : false,
                splitLine: {show: false},
                axisLabel: {show: false},
                axisTick: {show: false},
                axisLine: { lineStyle: { color: '#777' } },
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax',
                axisPointer: {
                    type: 'shadow',
                    label: {show: false},
                    triggerTooltip: true,
                    handle: {
                        show: true,
                        margin: 30,
                        color: '#B80C00'
                    }
                }
            }],
            yAxis: [{
                scale: true,
                splitNumber: 2,
                axisLine: { lineStyle: { color: '#777' } },
                splitLine: { show: true },
                axisTick: { show: false },
                axisLabel: {
                    inside: true,
                    formatter: '{value}\n'
                }
            }, {
                scale: true,
                gridIndex: 1,
                splitNumber: 2,
                axisLabel: {show: false},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false}
            }],
            grid: [{
                left: 20,
                right: 20,
                top: 90,
                height: 180
            }, {
                left: 20,
                right: 20,
                height: 40,
                top: 300
            }],
            graphic: [{
                type: 'group',
                left: 'center',
                top: 70,
                width: 300,
                bounding: 'raw',
                children: [{
                    id: 'MA5',
                    type: 'text',
                    style: {fill: colorList[1], font: labelFont},
                    left: 0
                }, {
                    id: 'MA10',
                    type: 'text',
                    style: {fill: colorList[2], font: labelFont},
                    left: 'center'
                }, {
                    id: 'MA20',
                    type: 'text',
                    style: {fill: colorList[3], font: labelFont},
                    right: 0
                }]
            }],
            series: [{
                name: 'Volume',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1,
                itemStyle: {
                    normal: {
                        color: '#7fbe9e'
                    },
                    emphasis: {
                        color: '#140'
                    }
                },
                data: volumes
            }, {
                type: 'candlestick',
                name: '日K',
                data: dataList,
                itemStyle: {
                    normal: {
                        color: '#ef232a',
                        color0: '#14b143',
                        borderColor: '#ef232a',
                        borderColor0: '#14b143'
                    },
                    emphasis: {
                        color: 'black',
                        color0: '#444',
                        borderColor: 'black',
                        borderColor0: '#444'
                    }
                }
            }, {
                name: 'MA5',
                type: 'line',
                data: dataMA5,
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    normal: {
                        width: 1
                    }
                }
            }, {
                name: 'MA10',
                type: 'line',
                data: dataMA10,
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    normal: {
                        width: 1
                    }
                }
            }, {
                name: 'MA20',
                type: 'line',
                data: dataMA20,
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    normal: {
                        width: 1
                    }
                }
            }]
        };
        stockChart.setOption(stockOption);
        stockChart.resize({
            width: screen.width,
            height: screen.height * 0.6
        });
    }

    showLineChart() {
        let lineChart = echarts.init(document.getElementById('line'));
        let dateArray = [];
        let closeList = [];
        for (let i = 0; i < this.dataList.length; i++) {
            let priceDate = this.dataList[i];
            dateArray.push(priceDate.date);
            closeList.push(Number(priceDate.closePrice));
        }

        let lineOption = {
            tooltip: {
                trigger: 'axis',
                position: function (pt) {
                    return [pt[0], '10%'];
                }
            },
            xAxis: {
                type: 'category',
                data: dateArray,
                boundaryGap : false,
                axisLine: { lineStyle: { color: '#777' } },
                axisLabel: {
                    formatter: function (value) {
                        return echarts.format.formatTime('HH:mm', value);
                    },
                    textStyle: {
                        color: '#ffffff'
                    }
                },
                min: 'dataMin',
                max: 'dataMax',
                axisPointer: {
                    show: true
                }
            },
            yAxis: {
                scale: true,
                axisLine: { lineStyle: { color: '#777' } },
                splitLine: { show: true },
                axisTick: { show: false },
                axisLabel: {
                    show: true,
                    inside: true,
                    textStyle: {
                        color: '#ffffff'
                    }
                },
            },
            series: [
                {
                    name:'分时',
                    type:'line',
                    smooth:true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        normal: {
                            color: '#828dff'
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: '#5251ff'
                            }, {
                                offset: 1,
                                color: '#767eff'
                            }])
                        }
                    },
                    data: closeList
                }
            ]
        };
        lineChart.setOption(lineOption);
        lineChart.resize({
            width: screen.width,
            height: screen.height * 0.6
        });
    }
}
